import { grids } from '../../utils/grids.js';
const app = getApp();
const pageData = {
  data: {
    width: 0,
    exp: wx.getStorageSync('rank'),
    colors: [],
    cube: 2,
    count: 0,
    seconds: 120,
    pause: false,
    id:[],
    word:[],
    //随机单词
    randomword: [],
    color0: "blue",
    color1: "blue",
    color2: "blue",
    color3: "blue",
    color4: "blue",
    color5: "blue",
    color6: "blue",
    color7: "blue",
    color8: "blue",
    color9: "blue",
    color10: "blue",
    color11: "blue",
    color12: "blue",
    color13: "blue",
    color14: "blue",
    color15: "blue",
    clickno:[16,16],//点击两次存储位置信息
    first:0,//第一点位置
    second:0,//第二点位置
    islocation:[4][4] //初始化每个位置的都占有词块，默认为1

  },
 
  onReady: function (e) {

    // 使用 wx.createAudioContext 获取 audio 上下文 context

    this.audioCtx = wx.createAudioContext('myAudio')
    this.audioCtx.setSrc('../../music/bgm.mp3')
    this.audioCtx.play()
  },

  audioPlay: function () {

    this.audioCtx.play()

  },

  audioPause: function () {

    this.audioCtx.pause()

  },
  onLoad: function () {
    var word1 = wx.getStorageSync('1');
    var word2 = wx.getStorageSync('2');
    var word3= wx.getStorageSync('3');
    var word4 = wx.getStorageSync('4');
    var word5 = wx.getStorageSync('5');
    var word6 = wx.getStorageSync('6');
    var word7 = wx.getStorageSync('7');
    var word8 = wx.getStorageSync('8');
    var word9 = wx.getStorageSync('9');
    var word10 = wx.getStorageSync('10');
    var word11 = wx.getStorageSync('11'); 
    var word12 = wx.getStorageSync('12');
    var word13= wx.getStorageSync('13');
    var word14 = wx.getStorageSync('14');
    var word15 = wx.getStorageSync('15');
    var word16 = wx.getStorageSync('16');
    if (word1) {
      this.setData({ 'word[0].text': word1 });
      console.log(this.data.word[0]);
    }
    if (word2) {
      this.setData({ 'word[1].text': word2});
    }
    if (word3) {
      this.setData({ 'word[2].text': word3 });
    }
    if (word4) {
      this.setData({ 'word[3].text': word4});
    }
    if (word5) {
      this.setData({ 'word[4].text': word5 });
    }
    if (word6) {
      this.setData({ 'word[5].text': word6 });
    }
    if (word7) {
      this.setData({ 'word[6].text': word7});
    }
    if (word8) {
      this.setData({ 'word[7].text': word8 });
    }
    if (word9) {
      this.setData({ 'word[8].text': word9 });
    }
    if (word10) {
      this.setData({ 'word[9].text': word10 });
    }
    if (word11) {
      this.setData({ 'word[10].text': word11});
    }
    if (word12) {
      this.setData({ 'word[11].text': word12 });
    }
    if (word13) {
      this.setData({ 'word[12].text': word13 });
    }
    if (word14) {
      this.setData({ 'word[13].text': word14 });
    }
    if (word15) {
      this.setData({ 'word[14].text': word15 });
    }
    if (word16) {
      this.setData({ 'word[15].text': word16});
    }
    this.initRandomList();
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          width: res.windowWidth
        });
      }
    });
    //初始化每个位置的都占有词块，默认都为1
    console.log("-----")
    for (var row = 0; row < 4; row++) {
      for (var col = 0; col < 4; col++) {
        this.setData({ ['islocation[' + row + '][' + col + '].text']: 1 });
      }
    }
    console.log("islocation:" + this.data.islocation[0][0].text)
  },

  initRandomList: function () {

    // 获取随机数列，
    for (var i = 0; i <16; i++) {
      var radm = Math.floor(Math.random() * 16);
      outer:
      while(1){
        for (var j= 0; j < i;j++){

          if (radm == this.data.id[j].text) {
            radm = Math.floor(Math.random() * 16);
            continue outer;
          }
        }
        break;
      }  
      this.setData({ ['id[' + i + '].text']: radm });  
      console.log(this.data.id[i].text);
      this.setData({ ['randomword[' + i + '].text']: this.data.word[radm].text });    
    }
  },
  
  onShow: function () {
    this._ren();
    this._timer();
    this.is_eliminate(0);//触发第一次clickno[]取值过程,防止游戏过程中出现NAM的现象
    
   
    

  },

  onUnload: function () {
    this.setData({
      pause: true
    });
    this._timer();
  },

  // 下一关
  goNext: function (e) {
    let next = e.currentTarget.dataset.next;
    if (next) {
      this.setData({
        score: this.data.score + 1,
      }
      );
      this._ren();
      wx.clearStorageSync()
    }
  },



  //点击单词块，返回按钮的位置
  clickBtn: function (x, y) {
    this.setData({
      clicknum : this.data.clicknum + 1,
    })
    
    console.log(clicknum);
    

  },

  //判断是否消除，是就消除，不是复原
  is_eliminate:function(value){  
    
    
    var id=0;
    for(;id<=15;id++){
      if ( value == this.data.id[id].text) {
        break;
      }
    }
    var r = this.switch_DyadicArray(id).row;
    var c = this.switch_DyadicArray(id).col;
    //console.log("row:" + this.switch_DyadicArray(id).row);
    //console.log("col:" + this.switch_DyadicArray(id).col);
    var isclick = this.data.islocation[r][c].text;
    //console.log("locmessage:" + this.data.islocation[r][c].text);

    if (isclick==1&&this.data.clickno[0].text == 16){
      this.setData({ 'clickno[0].text':value });
      
    }
    else if (isclick == 1 && this.data.clickno[0].text != 16){
 
        this.setData({ 'clickno[1].text': value });
      //console.log("click[0]:" + parseInt(this.data.clickno[0].text) + " click[1]:" +parseInt(this.data.clickno[1].text));
      //console.log("sum:" +parseInt(parseInt(this.data.clickno[0].text) + parseInt(this.data.clickno[1].text)))
        if  ((parseInt(this.data.clickno[0].text) + parseInt(this.data.clickno[1].text) )== 15) {
          for (var a=0;a<= 15;a++) {
            console.log("aa"+this.data.first);          
            if (this.data.clickno[0].text == this.data.id[a].text) {
              this.remove(a); 
              this.data.count = this.data.count+1;
              this.setData({ ['islocation[' + this.switch_DyadicArray(a).row + '][' + this.switch_DyadicArray(a). col + '].text']: 0 });
              break;
            }
          }
          for (var b=0; b<= 15;b++) {            
            if (this.data.clickno[1].text == this.data.id[b].text) {
              this.remove(b); 
              this.data.count = this.data.count + 1;
              if(this.data.count==16)
              {
                this.toSuccess();
               /* wx.redirectTo({
                  url: '../pass/pass'
                  
                });*/
              }
              this.setData({ ['islocation[' + this.switch_DyadicArray(b).row + '][' + this.switch_DyadicArray(b).col + '].text']: 0 });
              console.log(this.data.islocation[this.switch_DyadicArray(b).row][this.switch_DyadicArray(b).col]);
              break;
            }
          }          
                 
          }
                  
        else { 
          for (var a = 0; a <= 15; a++) {
            if (this.data.clickno[0].text == this.data.id[a].text) {
              this.backcolor(a);
              break;
            }
          }
          for (var b = 0; b <= 15; b++) {
            if (this.data.clickno[1].text == this.data.id[b].text) {
              this.backcolor(b);
              break;
            }
          }         
                     
        }
        this.setData({ 'clickno[0].text': 16 });
        //console.log(a + ":" + this.data.clickno[0].text);
        this.setData({ 'clickno[1].text': 16 });
        //console.log(b + ":" + this.data.clickno[1].text);
      }
    else if(isclick==0){
      this.remove(id);
    }

    
  },

  //传入是第几块的，返回二维数组位置信息
  switch_DyadicArray:function(id){
    var row,col;
    switch(id){
      case 0: { row = 0; col = 0 ; break; }
      case 1: { row = 0; col = 1; break; }
      case 2: { row = 0; col =2 ; break; }
      case 3: { row = 0; col =3 ; break; }
      case 4: { row = 1; col = 0; break; }
      case 5: { row = 1; col = 1; break; }
      case 6: { row = 1; col =2 ; break; }
      case 7: { row = 1; col =3 ; break; }
      case 8: { row = 2; col =0 ; break; }
      case 9: { row = 2; col =1 ; break; }
      case 10: { row =2 ; col =2 ; break; }
      case 11: { row = 2; col = 3; break; }
      case 12: { row = 3; col = 0; break; }
      case 13: { row = 3; col =1 ; break; }
      case 14: { row =3 ; col = 2; break; }
      case 15: { row =3 ; col = 3; break; }
    }
    return {row:row,col:col}
  },

  //传id值
  clickBtn0: function () {
    console.log(this.data.id[0].text);
    this.clickcolor(0);//点中变色
    this.is_eliminate(this.data.id[0].text);  
  },

  clickBtn1: function () {
    console.log(this.data.id[1].text);
    this.clickcolor(1);
    this.is_eliminate(this.data.id[1].text);
  
  },
  clickBtn2: function () {
    this.clickcolor(2);
    console.log(this.data.id[2].text);
    this.is_eliminate(this.data.id[2].text);
  },
  clickBtn3: function () {
    this.clickcolor(3);
    console.log(this.data.id[3].text);
    this.is_eliminate(this.data.id[3].text);
  },
  clickBtn4: function () {
    this.clickcolor(4);
    console.log(this.data.id[4].text);
    this.is_eliminate(this.data.id[4].text);
  },
  clickBtn5: function () {
    this.clickcolor(5);
    console.log(this.data.id[5].text);
    this.is_eliminate(this.data.id[5].text);
  },
  clickBtn6: function () {
    this.clickcolor(6);
    console.log(this.data.id[6].text);
    this.is_eliminate(this.data.id[6].text);
  },
  clickBtn7: function () {
    this.clickcolor(7);
    console.log(this.data.id[7].text);
    this.is_eliminate(this.data.id[7].text);
  }, 
  clickBtn8: function () {
    this.clickcolor(8);
    console.log(this.data.id[8].text);
    this.is_eliminate(this.data.id[8].text);
  },
  clickBtn9: function () {
    this.clickcolor(9);
    console.log(this.data.id[9].text);
    this.is_eliminate(this.data.id[9].text);
  },
  clickBtn10: function () {
    this.clickcolor(10);
    console.log(this.data.id[10].text);
    this.is_eliminate(this.data.id[10].text);
  },
  clickBtn11: function () {
    this.clickcolor(11);
    console.log(this.data.id[11].text);
    this.is_eliminate(this.data.id[11].text);
  },
  clickBtn12: function () {
    this.clickcolor(12);
    console.log(this.data.id[12].text);
    this.is_eliminate(this.data.id[12].text);
  },
  clickBtn13: function () {
    this.clickcolor(13);
    console.log(this.data.id[13].text);
    this.is_eliminate(this.data.id[13].text);
  },
  clickBtn14: function () {
    this.clickcolor(14);
    console.log(this.data.id[14].text);
    this.is_eliminate(this.data.id[14].text);
  },
  clickBtn15: function () {
    this.clickcolor(15);
    console.log(this.data.id[15].text);
    this.is_eliminate(this.data.id[15].text);
  },
 

  //判断一个拐点是否可消除，可以消除返回1，不能消除返回0
  oneCore: function (x1, y1, x2, y2) {
    let a = 1, b = 1;
    //沿水平
    for (let y = y1; y < y2; y++) {
      if (wordArray[x1][y] == 1) {
        a = 0;
        break;
      }
    }
    for (let x = x1; x <= x2; x++) {
      if (wordArray[x][y2] == 1) {
        a = 0;
        break;
      }
    }
    //沿垂直
    for (let x = x1; x <= x2; x++) {
      if (wordArray[x][y1] == 1) {
        b = 0;
        break;
      }
    }
    for (let y = y1; y <= y2; y++) {
      if (wordArray[x2][y] == 1) {
        b = 0;
        break;
      }
    }
    if (a == 0 && b == 0) {
      return 0;
    }
    else {
      return 1;
    }
  },

  //判断是否可以消除，可以消除返回1，不能返回0
  isEliminate: function (x1, y1, x2, y2) {
    //如果两点坐标在同一水平或垂直方向相邻或者中间没有障碍块，满足直线连接，可消除
    //水平方向
    if (x1 = x2) {
      if (y1 < y2) {
        if (y2 - y1 == 1)
          return 1;
        else {
          for (let y = y1; y < y2; y++) {
            if (wordArray[x1][y] == 1) {
              break;
            }
            return 1;
          }
        }
      }
      else {
        if (y1 - y2 == 1)
          return 1;
        else {
          for (let y = y2; y < y1; y++) {
            if (wordArray[x1][y] == 1) {
              break;
            }
            return 1;
          }
        }
      }
    }
    //沿垂直方向
    if (y1 = y2) {
      if (x1 < x2) {
        if (x2 - x1 == 1) return 1;
        else {
          for (let x = x1; x < x2; x++) {
            if (wordArray[x][y1] == 1) { break; }
            return 1;
          }
        }
      }
      else {
        if (x1 - x2 == 1) return 1;
        else {
          for (let x = x2; x < x1; x++) {
            if (wordArray[x][y1] == 1) { break; }
            return 1;
          }
        }
      }
    }

    //进一步判断有拐点的情况
    //第一点在左边，第二点在右边
    if (y1 < y2) {
      if (x1 < x2) {
        if (oneCore(x1, y1, x2, y2) == 1) return 1;//一个拐点可消除
        else {
          for (let x = 0; x <= 3; x++) {
            if (x < x1 && wordArray[x][y1] == 0 && oneCore(x, y1, x2, y2) == 1) return 1;
            if (x > x1 && wordArray[x][y1] == 0 && oneCore(y2, x2, y1, x) == 1) return 1;
            return 0;
          }
        }
      }
      else {
        if (oneCore(y2, x2, y1, x1) == 1) return 1;//一个拐点可消除
        else {
          for (let x = 0; x <= 3; x++) {
            if (x < x1 && wordArray[x][y1] == 0 && oneCore(x, y1, x2, y2) == 1) return 1;
            if (x > x1 && wordArray[x][y1] == 0 && oneCore(y2, x2, y1, x) == 1) return 1;
            return 0;
          }
        }
      }

    }
    //第一点在右边，第二点在左边
    else {
      if (x1 > x2) {
        if (oneCore(x2, y2, x1, y2) == 1) return 1;
        else {
          for (let x = 0; x <= 3; x++) {
            if (x < x2 && wordArray[x][y2] == 0 && oneCore(x, y2, x1, y1) == 1) return 1;
            if (x > x2 && wordArray[x][y2] == 0 && oneCore(y1, x1, y2, x) == 1) return 1;
            return 0;
          }
        }
      }
      else {
        if (oneCore(y1, x1, y2, x2) == 1) return 1;
        else {
          for (let x = 0; x <= 3; x++) {
            if (x < x2 && wordArray[x][y2] == 0 && oneCore(x, y2, x1, y1) == 1) return 1;
            if (x > x2 && wordArray[x][y2] == 0 && oneCore(y1, x1, y2, x) == 1) return 1;
            return 0;
          }
        }
      }
    }
  },

  //隐藏按钮
  remove: function (id) {
    switch(id)
    {
      case 0: this.setData({ color0: "removecolor" }); break;
      case 1: this.setData({ color1: "removecolor" }); break;
      case 2: this.setData({ color2: "removecolor" }); break;
      case 3: this.setData({ color3: "removecolor" }); break;
      case 4: this.setData({ color4: "removecolor" }); break;
      case 5: this.setData({ color5: "removecolor" }); break;
      case 6: this.setData({ color6: "removecolor" }); break;
      case 7: this.setData({ color7: "removecolor" }); break;
      case 8: this.setData({ color8: "removecolor" }); break;
      case 9: this.setData({ color9: "removecolor" }); break;
      case 10: this.setData({ color10: "removecolor" }); break;
      case 11: this.setData({ color11: "removecolor" }); break;
      case 12: this.setData({ color12: "removecolor" }); break;
      case 13: this.setData({ color13: "removecolor" }); break;
      case 14: this.setData({ color14: "removecolor" }); break;
      case 15: this.setData({ color15: "removecolor" }); break;
    }    
  },

  //点中变色
  clickcolor: function (id) {
    switch (id) {
      case 0: this.setData({ color0: "blueviolet" }); break;
      case 1: this.setData({ color1: "blueviolet" }); break;
      case 2: this.setData({ color2: "blueviolet" }); break;
      case 3: this.setData({ color3: "blueviolet" }); break;
      case 4: this.setData({ color4: "blueviolet" }); break;
      case 5: this.setData({ color5: "blueviolet" }); break;
      case 6: this.setData({ color6: "blueviolet" }); break;
      case 7: this.setData({ color7: "blueviolet" }); break;
      case 8: this.setData({ color8: "blueviolet" }); break;
      case 9: this.setData({ color9: "blueviolet" }); break;
      case 10: this.setData({ color10: "blueviolet" }); break;
      case 11: this.setData({ color11: "blueviolet" }); break;
      case 12: this.setData({ color12: "blueviolet" }); break;
      case 13: this.setData({ color13: "blueviolet" }); break;
      case 14: this.setData({ color14: "blueviolet" }); break;
      case 15: this.setData({ color15: "blueviolet" }); break;
    }
  },

  //恢复成原来的颜色
  backcolor: function (id) {
    switch (id) {
      case 0: this.setData({ color0: "blue" }); break;
      case 1: this.setData({ color1: "blue" }); break;
      case 2: this.setData({ color2: "blue" }); break;
      case 3: this.setData({ color3: "blue" }); break;
      case 4: this.setData({ color4: "blue" }); break;
      case 5: this.setData({ color5: "blue" }); break;
      case 6: this.setData({ color6: "blue" }); break;
      case 7: this.setData({ color7: "blue" }); break;
      case 8: this.setData({ color8: "blue" }); break;
      case 9: this.setData({ color9: "blue" }); break;
      case 10: this.setData({ color10: "blue" }); break;
      case 11: this.setData({ color11: "blue" }); break;
      case 12: this.setData({ color12: "blue" }); break;
      case 13: this.setData({ color13: "blue" }); break;
      case 14: this.setData({ color14: "blue" }); break;
      case 15: this.setData({ color15: "blue" }); break;
    }
  },
  //游戏成功
  toSuccess: function () {
    this.setData({
      pause: false
    });
    this.getRank();
    this.audioPause()
    wx.redirectTo({
     
      url: '../pass/pass'

    });
  },
  getRank: function () {
    var scnd = parseInt(this.data.seconds) + parseInt(wx.getStorageSync('exp'));
    console.log("exp"+scnd);
    wx.setStorageSync('exp', scnd);
    var rexp = wx.getStorageSync('exp');
    if (rexp > 100) {
      var newexp=rexp - 100;
      wx.setStorageSync('exp', newexp);
      var rank3 = parseInt(wx.getStorageSync('rank')) + 1;
      wx.setStorageSync('rank', rank3);
    }
  },
  // 暂停
  toPause: function () {
    this.setData({
      pause: true
    });
    this._timer();
  },

  // 继续
  toContinue: function () {
    this.setData({
      pause: false
    });
    this._timer();
  },

  // 计时器
  _timer: function () {
    let tm = setInterval(() => {
      let scnd = this.data.seconds;

      // 暂停
      if (this.data.pause) {
        clearInterval(tm);
        return;
      }

      // 结束
      if (scnd == 0) {
        clearInterval(tm);
        this._gameOver();
        return;
      }

      this.setData({
        seconds: scnd - 1
      });
    }, 1000);
  },

  // 游戏结束
  _gameOver: function () {
      wx.redirectTo({
        url: '../gameover/gameover'
      });
  },

  // 数据准备 & 渲染
  _ren: function () {
    let width = this.data.width;
    let score = this.data.score;
    let round = grids(score);
    let cube = round.cube;
    let total = cube * cube;
    let colorAry = new Array(total);
    let size = Math.floor(width / cube);

    colorAry.fill({
      color: round.mainColor,
      next: false,
      size: size
    }, 0, colorAry.length);

    let oneIndex = Math.floor(Math.random() * total);

    colorAry[oneIndex] = {
      color: round.oneColor,
      next: true,
      size: size
    };

    this.setData({
      cube: cube,
      colors: colorAry
    });
  }
};

Page(pageData);